﻿using FineUIPro;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyDataProcess;
using System.Data.SqlClient;
using KPI_SYSTEM.Code;
using System.Text;

namespace KPI_SYSTEM.baseData
{
    public partial class Role_Dict : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                btnDelete.OnClientClick = Grid1.GetNoSelectionAlertReference("请至少选择一项！");
                btnDelete.ConfirmText = String.Format("你确定要删除选中的&nbsp;<b><script>{0}</script></b>&nbsp;行数据吗？", Grid1.GetSelectedCountReference());

                LoadMenuData();
                // 绑定表格
                BindGrid();
            }
        }

        private void LoadMenuData()
        {
            

            DataSet ds = new DataSet();
            ds = GetMenuData();
            ds.Relations.Add("TreeRelation", ds.Tables[0].Columns["REC_ID"], ds.Tables[0].Columns["Parent_ID"]);

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                if (row.IsNull("Parent_ID"))
                {
                    FineUIPro.TreeNode node = new FineUIPro.TreeNode();
                    node.NodeID= row["REC_ID"].ToString();
                    node.Text = row["Menu_Name"].ToString();
                    Tree1.Nodes.Add(node);

                    ResolveSubTree(row, node);
                }
            }
        }

        private void ResolveSubTree(DataRow dataRow, FineUIPro.TreeNode treeNode)
        {
            DataRow[] rows = dataRow.GetChildRows("TreeRelation");
            if (rows.Length > 0)
            {
                // 如果是目录，则默认展开
                treeNode.Expanded = true;
                foreach (DataRow row in rows)
                {
                    FineUIPro.TreeNode node = new FineUIPro.TreeNode();
                    node.NodeID = row["REC_ID"].ToString();
                    node.Text = row["Menu_Name"].ToString();
                    treeNode.Nodes.Add(node);

                    ResolveSubTree(row, node);
                }
            }
        }

        #region BindGrid

        private void BindGrid()
        {
            DataTable table = GetSourceData();

            Grid1.DataSource = table;
            Grid1.DataBind();
        }



        #endregion

        #region Events

        protected void Grid1_PreRowDataBound(object sender, GridPreRowEventArgs e)
        {
            // 如果绑定到 DataTable，那么这里的 DataItem 就是 DataRowView
            DataRowView row = e.DataItem as DataRowView;
            int rowId = Convert.ToInt32(row["REC_ID"]);

            LinkButtonField editField = Grid1.FindColumn("Edit") as LinkButtonField;
            editField.OnClientClick = String.Format("showEditWindow('{0}');", rowId);
        }


        // 删除数据
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length > 0)
            {
                foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                {
                    int rowID = Convert.ToInt32(Grid1.DataKeys[rowIndex][0]);
                    DeleteRowByID(rowID);
                }

                BindGrid();
                ShowNotify("删除数据成功!（表格数据已重新绑定）");

            }

        }
        // 同步钉钉
        protected void btnSyncDingding_Click(object sender, EventArgs e)
        {
            try
            {
                List<DING_ROLE_INFO> rOLE_INFOs = new List<DING_ROLE_INFO>();
                rOLE_INFOs = DingHelper.GetRoleList();
                StringBuilder sqlUpdate = new StringBuilder();
                StringBuilder sqlInsert = new StringBuilder();
                foreach (DING_ROLE_INFO rOLE_INFO in rOLE_INFOs)
                {
                    int checkCount = (int)SqlHelper.ExecuteScalar(CommandType.Text, "SELECT COUNT(*) FROM ROLE_DICT WHERE ROLE_GROUP_ID='" + rOLE_INFO.ROLE_GROUP_ID + "' AND ROLE_CODE='" + rOLE_INFO.ROLE_ID + "'");
                    if (checkCount > 0)
                    {
                        sqlUpdate.Append("UPDATE ROLE_DICT SET ROLE_NAME='" + rOLE_INFO.ROLE_NAME + "',ROLE_GROUP_NAME='" + rOLE_INFO.ROLE_GROUP_NAME + "' WHERE ROLE_CODE='" + rOLE_INFO.ROLE_ID + "' AND ROLE_GROUP_ID='" + rOLE_INFO.ROLE_GROUP_ID + "';");
                    }
                    else
                    {
                        sqlInsert.Append("INSeRT INTO ROLE_DICT (ROLE_NAME,ROLE_CODE,ROLE_GROUP_ID,ROLE_GROUP_NAME,STATUS) VALUES ('" + rOLE_INFO.ROLE_NAME + "','" + rOLE_INFO.ROLE_ID + "','" + rOLE_INFO.ROLE_GROUP_ID + "','" + rOLE_INFO.ROLE_GROUP_NAME + "',1);");
                    }
                }
                if (!String.IsNullOrEmpty(sqlUpdate.ToString()))
                {
                    SqlHelper.ExecuteNonQuery(CommandType.Text, sqlUpdate.ToString());
                }
                if (!String.IsNullOrEmpty(sqlInsert.ToString()))
                {
                    SqlHelper.ExecuteNonQuery(CommandType.Text, sqlInsert.ToString());
                }
                ShowNotify("同步完成");
                BindGrid();
            }
            catch (Exception ex)
            {

                ShowNotify("同步失败："+ ex.Message); 
            }
        }
        //加载列表选项
        protected void btnAuthority_Click(object sender, EventArgs e)
        {
            Tree1.UncheckAllNodes();
            string strRoleID = authFormID.Text;
            SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SQL_Server"].ConnectionString);
            DataProcess dp1 = new DataProcess();
            DataSet ds1 = new DataSet();//创建dataset
            string sql = "SELECT * FROM ROLE_MENU_MAP_DICT WHERE ROLE_ID=" + strRoleID;
            conn.Open();
            ds1 = dp1.SqlService_Query(sql, conn);
            conn.Close();
            for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
            {
                if (Tree1.FindNode(ds1.Tables[0].Rows[i]["MENU_ID"].ToString()) != null)
                {
                    Tree1.FindNode(ds1.Tables[0].Rows[i]["MENU_ID"].ToString()).Checked = true;
                }
            }
            //Tree1.FindNode("suiping").Checked = true;
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int rowID = Convert.ToInt32(Grid1.DataKeys[e.RowIndex][0]);
                try
                {
                    DeleteRowByID(rowID);

                    BindGrid();
                    ShowNotify("删除数据成功!（表格数据已重新绑定）");
                }
                catch (Exception ex)
                {
                    ShowNotify("删除数据失败!");
                }
            }
        }


        // 保存数据
        protected void btnSave_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SQL_Server"].ConnectionString);
            DataProcess dp1 = new DataProcess();
            DataSet ds1 = new DataSet();//创建dataset

            string strRowID = hfFormID.Text;
            if (String.IsNullOrEmpty(strRowID))
            {
                // 新增
                string sql = "SELECT * FROM ROLE_DICT WHERE 1=2";
                SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, conn);//创建dataadapter
                SqlCommandBuilder cb = new SqlCommandBuilder(dataAdapter);//使用oraclecommand类和dataadapter类对数据库操作
                dataAdapter.Fill(ds1, "serverInfo");
                DataTable table = ds1.Tables[0];
                DataRow addRow = table.NewRow();
                addRow["ROLE_NAME"] = tbxFormROLE_NAME.Text.Trim();
                addRow["ROLE_CODE"] = tbxFormROLE_CODE.Text.Trim();
                addRow["ROLE_GROUP_NAME"] = tbxFormROLE_GROUP_NAME.Text.Trim();
                addRow["ROLE_GROUP_ID"] = tbxFormROLE_GROUP_ID.Text.Trim();
                addRow["STATUS"] = cbFormSTATUS.Checked;
                table.Rows.Add(addRow);
                dataAdapter.Update(table.GetChanges());
                table.AcceptChanges();
            }
            else
            {
                // 编辑
                int rowID = Convert.ToInt32(strRowID);
                string sql = "SELECT * FROM ROLE_DICT WHERE REC_ID=" + rowID;
                SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, conn);//创建dataadapter
                SqlCommandBuilder cb = new SqlCommandBuilder(dataAdapter);//使用oraclecommand类和dataadapter类对数据库操作
                dataAdapter.Fill(ds1, "serverInfo");
                DataTable table = ds1.Tables[0];
                DataRow currRow = table.Rows[0];

                currRow["REC_ID"] = rowID;
                currRow["ROLE_NAME"] = tbxFormROLE_NAME.Text.Trim();
                currRow["ROLE_CODE"] = tbxFormROLE_CODE.Text.Trim();
                currRow["ROLE_GROUP_NAME"] = tbxFormROLE_GROUP_NAME.Text.Trim();
                currRow["ROLE_GROUP_ID"] = tbxFormROLE_GROUP_ID.Text.Trim();
                currRow["STATUS"] = cbFormSTATUS.Checked;
                dataAdapter.Update(table.GetChanges());
                table.AcceptChanges();
            }


            // 重新绑定表格，并点击当前编辑或者新增的行
            BindGrid();
            PageContext.RegisterStartupScript(String.Format("F('{0}').selectRow('{1}');", Grid1.ClientID, strRowID) + Window1.GetHideReference());
        }

        // // 保存权限数据 未测试
        protected void btnSaveAuth_Click(object sender, EventArgs e)
        {
            string strRoleID = authFormID.Text;
            FineUIPro.TreeNode[] nodes = Tree1.GetCheckedNodes();

            SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SQL_Server"].ConnectionString);
            DataProcess dp1 = new DataProcess();
            DataSet ds1 = new DataSet();//创建dataset
            string sql = "SELECT * FROM ROLE_MENU_MAP_DICT WHERE ROLE_ID=" + strRoleID;
            SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, conn);//创建dataadapter
            SqlCommandBuilder cb = new SqlCommandBuilder(dataAdapter);//使用oraclecommand类和dataadapter类对数据库操作
            dataAdapter.Fill(ds1, "serverInfo");
            DataTable table = ds1.Tables[0];
            if (table.Rows.Count > 0)
            {
                for (int i = table.Rows.Count - 1; i >= 0; i--)
                {
                    table.Rows[i].Delete();
                }
                dataAdapter.Update(table.GetChanges());
                table.AcceptChanges();
            }
            if (nodes.Length > 0)
            {

                foreach (FineUIPro.TreeNode node in nodes)
                {
                    DataRow addRow = table.NewRow();
                    addRow["ROLE_ID"] = strRoleID;
                    addRow["MENU_ID"] = node.NodeID;
                    table.Rows.Add(addRow);  
                }
                dataAdapter.Update(table.GetChanges());
                table.AcceptChanges();
                ShowNotify("保存成功");
            }
            Window2.Hidden = true;
        }


        #endregion

        #region Data


        // 查询数据
        private DataTable GetSourceData()
        {
            SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SQL_Server"].ConnectionString);
            DataProcess dp1 = new DataProcess();
            DataSet ds1 = new DataSet();//创建dataset
            string sqlstr = "SELECT * FROM ROLE_DICT ";
            conn.Open();
            ds1 = dp1.SqlService_Query(sqlstr, conn);
            conn.Close();
            return ds1.Tables[0];
        }

        private DataSet GetMenuData()
        {
            SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SQL_Server"].ConnectionString);
            DataProcess dp1 = new DataProcess();
            DataSet ds1 = new DataSet();//创建dataset
            string sqlstr = "SELECT * FROM MENU_DICT ";
            conn.Open();
            ds1 = dp1.SqlService_Query(sqlstr, conn);
            conn.Close();
            return ds1;
        }

        // 根据行ID来删除行数据
        private void DeleteRowByID(int rowID)
        {
            SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SQL_Server"].ConnectionString);
            DataProcess dp1 = new DataProcess();
            try
            {
                string sqlstr = "DELETE FROM ROLE_DICT WHERE REC_ID=" + rowID;
                conn.Open();
                string deleteresult = "";
                deleteresult = dp1.SqlService_updateSQL(sqlstr, conn);
                conn.Close();
                if (deleteresult == "1")
                {
                }
                else
                {
                    throw new Exception("删除失败！");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("删除失败！");
            }
        }



        #endregion




    }
}